require("../../assets/css/normalize.css");
require("../../assets/css/reset.css");
require("../../assets/fonts/iconfont.css");
require("./sports_crouse_play.less");
const dom = require("../../utils/dom.js");
const axios = require("axios");
document.addEventListener("DOMContentLoaded", function () {
	let fragments = JSON.parse(localStorage.getItem("fragments"));
	console.log(fragments);
	let n = 0;
	let video = dom.get("#video");
	let proc = dom.get(".progress-b");
	let timer = null;
	let starttime = Date.now();
	let duration = 0;
	function play() {
		dom.get("#cur").textContent = n + 1;
		dom.get("#cur-b").textContent = fragments.length;
		dom.get("#title").textContent = fragments[n].title;
		dom.get("#video").src =
			"http://fitness.h5.itsource.cn:3701" + fragments[n].videoUrl;
		video.play();
		//进度条
		timer = setInterval(function () {
			proc.style.width = (100 * video.currentTime) / video.duration + "%";
		}, 100);
	}
	play();
	//自动播放下一节
	video.addEventListener("ended", function () {
		n++;
		if (n < fragments.length) {
			play();
		}
	});
	// 上一节
	dom.get(".icon-24gl-previous").addEventListener("click", function () {
		n--;
		if (n >= 0) {
			play();
		} else {
			n = 0;
		}
	});
	// /下一节
	dom.get(".icon-24gl-next").addEventListener("click", function () {
		n++;
		if (n < fragments.length) {
			play();
		} else {
			n = fragments.length - 1;
		}
	});
	//隐藏蒙层
	dom.get("#box1").addEventListener("click", function () {
		this.style.display = "none";
		dom.get("#box2").style.display = "none";
		video.play();
	});
	//点击暂停显示蒙层
	dom.get(".icon-zanting").addEventListener("click", function () {
		dom.get("#box1").style.display = "block";
		dom.get("#box2").style.display = "flex";
		video.pause();
		//计算时间
		duration += Date.now() - starttime;
	});
	// 继续训练
	dom.get(".icon-guanji").addEventListener("click", function () {
		dom.get("#box1").style.display = "none";
		dom.get("#box2").style.display = "none";
		video.play();
		starttime = Date.now();
	});
	// 结束训练
	let token = localStorage.getItem("token");
	axios.defaults.headers.common["Authorization"] = "Bearer " + token;
	dom.get("#end").addEventListener("click", function () {
		duration = Math.floor(duration / 1000);
		let calorie = Math.ceil(duration * 1.57);

		axios
			.post("http://fitness.h5.itsource.cn:3701/api/exercise/save", {
				type: 2,
				duration,
				calorie,
			})
			.then((res) => {
				if (res.data.errno === 0) {
					alert("训练结束，欢迎下次再来");
					location.href = "sports_crouse.html";
				}
			});
	});
});
